//
//  AlertViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/15.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "AlertViewController.h"
#import "SetAlertViewController.h"
#import "AppDelegate.h"

#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"
@interface AlertViewController ()

@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;
@property (nonatomic,weak) AppDelegate *mydelegate;
@property (nonatomic,strong) Watch *selectWatch;
@end

@implementation AlertViewController
@synthesize navLeftButton;
@synthesize navRightButton;
@synthesize addSafeAreaTableViewCell;
@synthesize tableView;
@synthesize tableViewHeight;
@synthesize alertTableViewCell;
@synthesize mydelegate;
-(void)dealloc
{
    self.syncManager=NULL;
    self.dataManager=NULL;
    [mydelegate.alertDetailsDataArray removeAllObjects];
    mydelegate.alertDetailsDataArray=NULL;
    mydelegate=NULL;
    self.selectWatch=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    mydelegate=[[UIApplication sharedApplication] delegate];
    mydelegate.alertDetailsDataArray=[[NSMutableArray alloc] init];
    self.canDelete=YES;
    if(mydelegate!=NULL&& mydelegate.isAdmin==YES)
    {
        self.navigationItem.rightBarButtonItem=navRightButton;
        [self initNavButton];
        self.navigationItem.rightBarButtonItem=nil;
    }
    [self initDataProxy];
     User *user=[User sharedSingleton];
    if(user==NULL||user.uid==NULL)
        return;
    self.selectWatch=[self.dataManager getActiveWatch:user.uid];
    [self initData];
    [self worktable];
    
    // Do any additional setup after loading the view from its nib.
}

-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
}

-(void)initData
{

    UIActivityIndicatorView *loadingView=[LeoMsg showLoadingView];
    [self.view addSubview:loadingView];
    [loadingView startAnimating];
    
    if(self.syncManager==NULL)
        return;
    [self.syncManager getReminders:self.selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        
        if (result==SUCESS)
        {
            [mydelegate.alertDetailsDataArray removeAllObjects];
            NSArray *alertArray=[self.dataManager getReminderList:self.selectWatch.deviceUid];
            for (int i=0;i<alertArray.count;i++)
            {
                NSLog(@"第%d个",i);
                Reminder *reminder=[[Reminder alloc] init];
                reminder=[alertArray objectAtIndex:i];
                
                NSString *remindActiveStr;
                if (reminder.is_active){remindActiveStr=@"1";}else{remindActiveStr=@"0";}
                NSMutableDictionary *dicOne = [NSMutableDictionary dictionaryWithObjectsAndKeys:reminder.remindTime,@"time",reminder.title,@"details",reminder.cycle,@"rate",remindActiveStr,@"status",reminder.reminder_id,@"remindID",nil];
                [mydelegate.alertDetailsDataArray addObject:dicOne];
            }
            [tableView reloadData];
            [loadingView stopAnimating];
        }
        else
        {
            [loadingView stopAnimating];
            [Tooler showHttpMsg:result description:description msg:@"获取闹钟数据失败"];
        }
        
        
    }];

    
}


-(void)viewWillAppear:(BOOL)animated{
    [mydelegate.alertDetailsDataArray removeAllObjects];
    //[self initData];
    NSArray *alertArray=[self.dataManager getReminderList:self.selectWatch.deviceUid];
    for (int i=0;i<alertArray.count;i++)
    {
        NSLog(@"第%d个",i);
        Reminder *reminder=[[Reminder alloc] init];
        reminder=[alertArray objectAtIndex:i];
        
        NSString *remindActiveStr;
        if (reminder.is_active){remindActiveStr=@"1";}else{remindActiveStr=@"0";}
        NSMutableDictionary *dicOne = [NSMutableDictionary dictionaryWithObjectsAndKeys:reminder.remindTime,@"time",reminder.title,@"details",reminder.cycle,@"rate",remindActiveStr,@"status",reminder.reminder_id,@"remindID",nil];
        [mydelegate.alertDetailsDataArray addObject:dicOne];
    }
    [tableView reloadData];
    //[self addAllCellLines];
}
-(void)viewDidAppear:(BOOL)animated{
    //[tableView reloadData];
    
}

- (void)initNavButton {

    [navRightButton setTarget:self];
    [navRightButton setAction:@selector(deleteAction)];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)deleteAction{
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    if (self.tableView.editing)
    {
        [self.navRightButton setTitle:@"删除"];
    }
    else
    {
        [self.navRightButton setTitle:@"编辑"];
    }
}

-(void)worktable{

    [tableView setAllowsSelectionDuringEditing:YES];


    self.automaticallyAdjustsScrollViewInsets=NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.delegate=self;
    tableView.dataSource=self;
    
    UINib *cellalert = [UINib nibWithNibName:@"AlertTableViewCell" bundle:nil];
    [tableView registerNib:cellalert forCellReuseIdentifier:@"alerttablecell"];
    self.alertTableViewCell  = [tableView dequeueReusableCellWithIdentifier:@"alerttablecell"];
    
    UINib *cellAdd = [UINib nibWithNibName:@"AddSafeAreaTableViewCell" bundle:nil];
    [tableView registerNib:cellAdd forCellReuseIdentifier:@"addSafeAreaCell"];
    self.addSafeAreaTableViewCell  = [tableView dequeueReusableCellWithIdentifier:@"addSafeAreaCell"];
    
//    tableView.estimatedRowHeight = 80;
//    tableView.rowHeight = UITableViewAutomaticDimension;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}
-(void)switchAction:(UISwitch*)sender
{
    int x=sender.tag-100;
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSMutableDictionary *dicOne=[myDelegate.alertDetailsDataArray objectAtIndex:x];
    NSString *remindID=[dicOne valueForKey:@"remindID"];
    Reminder *remind=[self.dataManager getReminder:remindID];
    if (remind.is_active)
    {
        remind.is_active=NO;
    }
    else
    {
        remind.is_active=YES;
    }
    [self.syncManager setReminder:self.selectWatch.deviceUid reminder:remind completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        
        if (result==SUCESS)
        {
            //[self.navigationController popViewControllerAnimated:YES];
            NSLog(@"%@",description);
        }
        
    }];
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row<mydelegate.alertDetailsDataArray.count){
        
        NSMutableDictionary *dicOne=[mydelegate.alertDetailsDataArray objectAtIndex:[indexPath row]];
        //NSString *remindID=[dicOne valueForKey:@"remindID"];
        
        
        NSDictionary *subdic=[[NSDictionary alloc]init];
        subdic=[mydelegate.alertDetailsDataArray objectAtIndex:indexPath.row];
        NSString *detail=[NSString stringWithFormat:@"%@,%@",[self changeSilentCycle:[subdic objectForKey:@"rate"]],[subdic objectForKey:@"details"]];
        
        if (detail.length>20){
            //NSLog(@"CELL高度%d",detail.length);
            return 80+20;
        }
     
    }
    
    
    return 80;
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    CGRect rect = [UIScreen mainScreen].bounds;
    if(mydelegate==NULL)
        return 0;
    if(mydelegate.isAdmin==NO)
    {
        if (80 * mydelegate.alertDetailsDataArray.count < rect.size.height) {
            tableViewHeight.constant = 80 * mydelegate.alertDetailsDataArray.count;
        }
        else
            tableViewHeight.constant = rect.size.height - 80;
        return mydelegate.alertDetailsDataArray.count;
    }
    else
    {
        if (80 * (mydelegate.alertDetailsDataArray.count+1) < rect.size.height) {
            tableViewHeight.constant = 80 * (mydelegate.alertDetailsDataArray.count+1);
        }
        else
            tableViewHeight.constant = rect.size.height - 80;
        return mydelegate.alertDetailsDataArray.count+1;
    }

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if(indexPath.row == myDelegate.alertDetailsDataArray.count){
        AddSafeAreaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addSafeAreaCell"];
        cell.navController=self.navigationController;
        cell=[self addCellLine:cell forIndex:indexPath.row];
        if (self.mydelegate.alertDetailsDataArray.count>=10)
        {
            cell.hidden=YES;
        }
        return cell;
    }
    AlertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"alerttablecell"];
    cell.navController=self.navigationController;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell = [cell getandSetData:[myDelegate.alertDetailsDataArray objectAtIndex:indexPath.row]];
    
    
    //Switch事件
    UISwitch *switchButton=[[UISwitch alloc]init];
    switchButton=(UISwitch *)cell.alertOnOff;
    switchButton.tag=100+[indexPath row];
    if(mydelegate.isAdmin==NO)
    {
        cell.alertOnOff.enabled=NO;
    }
    else
    {
        [cell.alertOnOff addTarget:self action:@selector(switchAction:)forControlEvents:UIControlEventValueChanged];
    }
    cell=[self addCellLine:cell forIndex:indexPath.row];
    return cell;
}

-(void)OnAndOffAction:(id)sender{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    UISwitch *sSwitch = (UISwitch*)sender;
    int x = sSwitch.tag - 1200;
    NSMutableDictionary *dicTemp = [myDelegate.alertDetailsDataArray objectAtIndex:x];
    if (sSwitch.isOn) {
        [dicTemp setValue:@"1" forKey:@"status"];
    }
    else {
        [dicTemp setValue:@"0" forKey:@"status"];
    }
    [myDelegate.alertDetailsDataArray replaceObjectAtIndex:x withObject:dicTemp];
    NSLog(@"%d",x);
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if(myDelegate.isAdmin==NO){
        return UITableViewCellEditingStyleNone;
    }
    else{
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.canDelete==NO)
        return;
    self.canDelete=NO;
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    UIActivityIndicatorView *loadingView=[LeoMsg showLoadingView];
    [self.view addSubview:loadingView];
    [loadingView startAnimating];

    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSArray *indexPaths = @[indexPath];
        //deleteRows++;
        //删除数据库的数据
        User *user=[User sharedSingleton];
        NSString *userId=user.uid;
        Watch *watch=[self.dataManager getActiveWatch:userId];
        NSString *watchId=watch.deviceUid;
        NSMutableDictionary *dicOne=[myDelegate.alertDetailsDataArray objectAtIndex:[indexPath row]];
        NSString *remindID=[dicOne valueForKey:@"remindID"];
        [self.syncManager deleteReminder:watchId reminderId:remindID completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            //NSLog(@"删除成功！");
            if(result==SUCESS)
            {
                
                [myDelegate.alertDetailsDataArray removeObjectAtIndex:[indexPath row]];  //删除数组里的数据
                [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];  //删除对应数据的cell
                [tableView reloadData];
                [loadingView stopAnimating];
            }
            else
            {
                [Tooler showHttpMsg:result description:description msg:@"删除闹钟失败"];
                [loadingView stopAnimating];
            }
            self.canDelete=YES;
        }];

    }
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if (indexPath.row==myDelegate.alertDetailsDataArray.count) {
        return NO;
    }
    else
        return YES;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if(myDelegate!=NULL&&myDelegate.isAdmin==NO)
        return;
    if(indexPath.row == myDelegate.alertDetailsDataArray.count){
        
        if (myDelegate.alertDetailsDataArray.count>=10)
        {
            [LeoMsg showMsg:@"闹钟最多只能设置10个"];
            return;
        }
        
        SetAlertViewController *setAlertViewController = [[SetAlertViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
        setAlertViewController.ifAdd=@"YES";
        [self.navigationController pushViewController:setAlertViewController animated:YES];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        //need disable HighLight after push to other Controller
    }
    else
    {
        
        NSMutableDictionary *dicOne=[myDelegate.alertDetailsDataArray objectAtIndex:[indexPath row]];
        NSString *remindID=[dicOne valueForKey:@"remindID"];
        
        
        NSDictionary *subdic=[[NSDictionary alloc]init];
        subdic=[myDelegate.alertDetailsDataArray objectAtIndex:indexPath.row];
        NSString *time=[NSString stringWithFormat:@"%@",[subdic objectForKey:@"time"]];
        
        
        SetAlertViewController *setAlertViewController = [[SetAlertViewController alloc]init];
        self.hidesBottomBarWhenPushed = YES;
        setAlertViewController.ifAdd=@"NO";
        setAlertViewController.dateString=time;
        setAlertViewController.rateString=[self changeSilentCycle:[NSString stringWithFormat:@"%@",[subdic objectForKey:@"rate"]] ];
        setAlertViewController.titleString=[NSString stringWithFormat:@"%@",[subdic objectForKey:@"details"]];
        
        
        User *user=[User sharedSingleton];
        NSString *userId=user.uid;
        
        Watch *watch=[self.dataManager getActiveWatch:userId];
        NSString *watchId=watch.deviceUid;
        NSArray *alertArray=[self.dataManager getReminderList:watchId];
        Reminder *reminder=[[Reminder alloc]init];
        reminder=[alertArray objectAtIndex:indexPath.row];
        setAlertViewController.origianlReminder=reminder;
        
        setAlertViewController.remindIDString=remindID;
        [self.navigationController pushViewController:setAlertViewController animated:YES];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

    
}
-(NSString *)changeSilentCycle:(NSString *)cycle
{
    NSString *newCycle=@"";
    
    if ([cycle isEqualToString:@"1,2,3,4,5,6,7"]){return @"每天";}
    
    for (int i=0;i<cycle.length;i++)
    {
        if (i%2==0)
        {
            NSRange range = NSMakeRange(i, 1);
            NSString *subString = [cycle substringWithRange:range];
            if ([subString isEqual:@"1"]){newCycle=[newCycle stringByAppendingString:@"周一,"];}
            if ([subString isEqual:@"2"]){newCycle=[newCycle stringByAppendingString:@"周二,"];}
            if ([subString isEqual:@"3"]){newCycle=[newCycle stringByAppendingString:@"周三,"];}
            if ([subString isEqual:@"4"]){newCycle=[newCycle stringByAppendingString:@"周四,"];}
            if ([subString isEqual:@"5"]){newCycle=[newCycle stringByAppendingString:@"周五,"];}
            if ([subString isEqual:@"6"]){newCycle=[newCycle stringByAppendingString:@"周六,"];}
            if ([subString isEqual:@"7"]){newCycle=[newCycle stringByAppendingString:@"周日,"];}
        }
        
    }
    if ([newCycle isEqualToString:@""])
    {
        return newCycle;
    }
    else
    {
        NSRange range = NSMakeRange(0, newCycle.length-1);
        newCycle = [newCycle substringWithRange:range];
        return newCycle;
    }
}

-(UITableViewCell *)addCellLine:(UITableViewCell *)cell forIndex:(int)index
{
    UILabel *orignal=[cell viewWithTag:999];
    if (orignal!=nil){
        [orignal removeFromSuperview];
    }
    NSArray *dic=self.mydelegate.alertDetailsDataArray;
    UILabel *line;
    NSLog(@"第%d个 cell宽度%f",index,cell.frame.size.height);
    if ((index==dic.count)||(index>=9))
    {
        
        line=[[UILabel alloc]initWithFrame:CGRectMake(0, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-0, 1)];
    }
    else
    {
        AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
        if((myDelegate.isAdmin==NO)&&(index==dic.count-1)){
            line=[[UILabel alloc]initWithFrame:CGRectMake(0, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-0, 1)];
        }
        else{
            line=[[UILabel alloc]initWithFrame:CGRectMake(20, cell.frame.size.height-1, [UIScreen mainScreen].bounds.size.width-20, 1)];
        }

    }
    line.backgroundColor=[UIColor colorWithRed:226/255.0 green:226/255.0 blue:228/255.0 alpha:1.0];
    line.tag=999;
    [cell addSubview:line];
    
    return cell;
}

//-(void)addAllCellLines{
// 
//    NSArray *cellArray=[tableView visibleCells];
//    for (int i=0;i<cellArray.count;i++){
//        UITableViewCell *cell=[cellArray objectAtIndex:i];
//        if (cell!=nil){
//            cell=[self addCellLine:cell forIndex:i];
//        }
//    
//    }
//    
//}
@end
